/* 
 * Programme simulant la gestion d'une imprimante
 */

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define N 10

int i=0;

void *impression(void *arg){
  char *nomFic = (char *) arg;
  printf("Debut d'impression de \"%s\"...\n", nomFic);
  sleep(5); /* Simule la lenteur de l'impression */
  printf("...Fin d'impression de \"%s\"...\n", nomFic);
  i-=1;
  pthread_exit(NULL);
}

void attenteImpression(){
  char nomFic[80];
  char *nomRecup;
  int rc;
  pthread_t threads[N];
  do {
    printf("Nom du fichier a imprimer (taper '0' pour terminer) ? ");
    scanf("%s", nomFic);
    if (strcmp(nomFic,"0") == 0){
      break;
    }
    /*Creation du thread*/
    nomRecup = malloc(strlen(nomFic) + 1);
    if (nomRecup < 0) { error(EXIT_FAILURE, rc, "malloc"); }
    strcpy(nomRecup,nomFic);
    rc = pthread_create(&threads[i], NULL, impression, nomRecup);
    if(rc) {
	    error(EXIT_FAILURE, rc, "pthread_create");
    }
    /*Detachement */
    if (pthread_detach(threads[i]) != 0) {
      error(EXIT_FAILURE, rc, "pthread_detach");
    } 
    i+=1;
  }while (1);
  printf("Au revoir\n");

}

int main(){

  attenteImpression();
  return EXIT_SUCCESS;

}
